//
//  WaitForBuzz.cpp
//  QuizMaster
//
//  Created by Jeppe Nielsen on 3/23/15.
//  Copyright (c) 2015 Jeppe Nielsen. All rights reserved.
//

#include "WaitForBuzz.hpp"
#include "GameWorld.hpp"
#include "MathHelper.hpp"
#include "SoundSystem.hpp"

using namespace Nano;

void WaitForBuzz::Initialize() {

    buzzer.AddBuzzer(0, 0);
    buzzer.AddBuzzer(1, 1);
    buzzer.AddBuzzer(2, 2);
    buzzer.AddBuzzer(3, 3);
    
    gui = Parent().gui;
    
    Vector2 size(10,1.0f);
    bar = gui->CreateControl(0, "Background", Vector3(0,-3,0), size);
    bar->GetComponent<Transform>()->Anchor = size*0.5f;
    bar->GetComponent<Transform>()->Position = Vector3(0,-10,0);
    
    buzzerSound = Parent().world.CreateObject();
    buzzerSound->AddComponent<Sound>()->LoadFromWav("buzzer.wav");
    buzzerSound->AddComponent<SoundEmitter>()->Looping = false;
    buzzerSound->GetComponent<SoundEmitter>()->Playing = false;
    
    buzzer.OnBuzz += event_handler(this, &WaitForBuzz::BuzzerDown);
    Input.ButtonDown += event_handler(this, &WaitForBuzz::ButtonDown);
    
    giveUpButton = gui->CreateLabelControl(0, "Background", 0, {1,1}, Parent().font, "Give up", 0.3f);
    giveUpButton->GetComponent<Touchable>()->Click += event_handler(this, &WaitForBuzz::GiveUpButtonClicked);
    giveUpButton->GetComponent<Material>()->Mask = 1;
    giveUpButton->Children()[0]->GetComponent<Material>()->Mask = 1;
    giveUpButton->GetComponent<Transform>()->Position = Vector2(-5,-20);
}

void WaitForBuzz::ButtonDown(std::string button) {
    BuzzerDown(0);
}

void WaitForBuzz::Update(float dt) {
    buzzer.Update(dt);
}

void WaitForBuzz::Render() {
    
}

void WaitForBuzz::Enabled() {
    //bar->ToFront();
    //bar->GetComponent<Transform>()->Position = Vector3(0,-3,0);
    buzzer.Bind(&Parent().bigButtonManager);
    
    buzzer.AllowAll();
    
    int numberOfPlayers = 0;
    for (int i=0; i<4; i++) {
        if (Parent().data.Players[i].IsPlaying) {
            numberOfPlayers++;
        }
    }
    
    int disabledBuzzersCount = 0;
    for (int i=0; i<4; i++) {
        if (!Parent().data.Players[i].BuzzerEnabled) {
            buzzer.DisableBuzzer(i);
            disabledBuzzersCount++;
        }
    }
    giveUpButton->ToFront();
    giveUpButton->GetComponent<Transform>()->Position = Vector2(-5,-3);

    if (disabledBuzzersCount==numberOfPlayers) {
        GiveUpButtonClicked(Nano::TouchData());
    }
}

void WaitForBuzz::Disabled() {
    //bar->GetComponent<Transform>()->Position = Vector3(0,10,0);
    giveUpButton->GetComponent<Transform>()->Position = Vector2(-5,-20);
    buzzer.Unbind();
}

void WaitForBuzz::BuzzerDown(int index) {
    buzzerSound->GetComponent<SoundEmitter>()->Emit();
    Parent().data.PlayerToAnswerQuestion = &Parent().data.Players[index];
    Parent().CurrentState = "AnswerQuestion";
}

void WaitForBuzz::GiveUpButtonClicked(Nano::TouchData d) {
    Parent().data.PlayerToAnswerQuestion = 0;
    Parent().CurrentState = "AnswerQuestion";
}

